package com.koushikdutta.ion.loader;

import com.example.ohosasynclibrary.async.DataEmitter;
import com.example.ohosasynclibrary.async.future.Future;
import com.example.ohosasynclibrary.async.future.FutureCallback;
import com.example.ohosasynclibrary.async.future.SimpleFuture;
import com.example.ohosasynclibrary.async.http.AsyncHttpRequest;
import com.example.ohosasynclibrary.async.stream.InputStreamDataEmitter;
import com.koushikdutta.ion.Ion;
import com.koushikdutta.ion.ResponseServedFrom;
import com.koushikdutta.ion.UriUtils;
import com.koushikdutta.ion.bitmap.BitmapInfo;
import ohos.agp.utils.Point;
import ohos.app.Context;
import ohos.global.resource.Resource;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.utils.net.Uri;

/**
 * Created by koush on 6/20/14.
 */
public class ResourceLoader extends StreamLoader {

    @Override
    public Future<BitmapInfo> loadBitmap(final Context context, final Ion ion, final String key, final String uri, final int resizeWidth, final int resizeHeight, final boolean animateGif) {
        if (uri == null || !uri.startsWith("dataability:/"))
            return null;
        if (!UriUtils.isResourceUri(context, Uri.parse(uri))) {
            return null;
        }

        final SimpleFuture<BitmapInfo> ret = new SimpleFuture<BitmapInfo>();

        Ion.getBitmapLoadExecutorService().execute(new Runnable() {
            @Override
            public void run() {
                try {
//                    final File file = new File(Uri.parse(uri).getDecodedPath());
//                    String path = Uri.parse(uri).getDecodedPath();
//                    String mimeType = "image/*";
//                    if (!TextUtils.isEmpty(path) && path.contains(".")) {
//                        mimeType = "image/".concat(path.substring(path.lastIndexOf(".") + 1).toLowerCase());
//                    }
//                    ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
//                    sourceOptions.formatHint = mimeType;
//                    ImageSource imageSource = ImageSource.create(file, sourceOptions);
                    ImageSource imageSource = UriUtils.uriToImageSource(context, Uri.parse(uri));
                    ImageSource.DecodingOptions options = ion.getBitmapCache().prepareBitmapOptions(imageSource.getImageInfo().size, resizeWidth, resizeHeight);
                    Point size = new Point(options.desiredSize.width, options.desiredSize.height);
                    BitmapInfo info;

//                    if (animateGif && TextUtils.equals("image/gif", mimeType)) {
//                        FileInputStream fin = new FileInputStream(file);
//                        try {
//                            info = loadGif(key, size, fin, mimeType);
//                        } finally {
//                            StreamUtility.closeQuietly(fin);
//                        }
//                    } else {
                        PixelMap bitmap = imageSource.createPixelmap(options);
                        if (bitmap == null)
                            throw new Exception("Bitmap failed to load");
                        Point point = new Point(bitmap.getImageInfo().size.width, bitmap.getImageInfo().size.height);
                        info = new BitmapInfo(key, "image/*", bitmap, point);
//                    }
                    info.servedFrom = ResponseServedFrom.LOADED_FROM_CACHE;
                    ret.setComplete(info);
                } catch (OutOfMemoryError e) {
                    ret.setComplete(new Exception(e), null);
                } catch (Exception e) {
                    ret.setComplete(e);
                }
            }
        });

        return ret;
    }

    @Override
    public Future<DataEmitter> load(final Ion ion, final AsyncHttpRequest request, final FutureCallback<LoaderEmitter> callback) {
        if (request.getUri().getScheme() == null || !request.getUri().getScheme().equals("dataability"))
            return null;

        final InputStreamDataEmitterFuture ret = new InputStreamDataEmitterFuture();
        ion.getHttpClient().getServer().post(new Runnable() {
            @Override
            public void run() {
                try {
//                    FileInputStream stream = new FileInputStream(new File(URI.create(request.getUri().toString())));
                    Resource stream = UriUtils.uriToResource(ion.getContext(), request.getUri());
                    int available = stream.available();
                    InputStreamDataEmitter emitter = new InputStreamDataEmitter(ion.getHttpClient().getServer(), stream);
                    ret.setComplete(emitter);
                    callback.onCompleted(null, new LoaderEmitter(emitter, available, ResponseServedFrom.LOADED_FROM_CACHE, null, null));
                } catch (Exception e) {
                    ret.setComplete(e);
                    callback.onCompleted(e, null);
                }
            }
        });
        return ret;
    }
}
